<?php

namespace App\Think\Org;
use App\Think\Redis;

/**
 * Token操作类
 */
class Token
{

    public static $instance;
    public static $tokenPrefix = 'tk:';
    public static $userPrefix  = 'uts:';

    /**
     *
     * @param array $options 参数
     * @return Auth
     */
    public static function init($options = [])
    {
        if (is_null(self::$instance)) {
            self::$instance = new static($options);
        }
        return self::$instance;
    }

    /**
     * 判断Token是否可用
     * @param string $token Token标识
     * @return bool
     */
    public static function check($token, $user_id)
    {
        $_user_id = Redis::init()->get( self::getTokenKey($token), $default);
        if($_user_id == $user_id) return true;
        return false;
    }

    /**
     * 读取Token
     * @access public
     * @param  string $token   Token标识
     * @param  mixed  $default 默认值
     * @return mixed
     */
    public static function get($token, $default = false)
    {
        $value = Redis::init()->get( self::getTokenKey($token));
        return ['token'=>$token, 'user_id'=>$value];
    }

    /**
     * 写入Token
     * @access public
     * @param  string   $token   Token标识
     * @param  mixed    $user_id 存储数据
     * @param  int|null $expire  有效时间 0为永久
     * @return boolean
     */
    public static function set($token, $user_id, $expire = null)
    {
        $redis = Redis::init();
        $redis->sAdd( self::getUserKey($user_id), self::getTokenKey($token) );
        return $redis->set( self::getTokenKey($token), $user_id, $expire);
    }

    /**
     * 删除Token
     * @access public
     * @param  string $token Token标识
     * @return boolean
     */
    public static function delete($token)
    {
        $redis = Redis::init();
        $data = self::get($token);
        if ($data) {
            $key = self::getTokenKey($token);
            $user_id = $data;
            $redis->del($key);
            $redis->sRem(self::getUserKey($user_id), $key);
        }
        return true;
    }

    /**
     * 获取指定用户Token
     * @access public
     * @param  string $token Token标记
     */
    public static function tokens($user_id = null)
    {
        return Redis::init()->sMembers( self::getUserKey($user_id) );
    }

    /**
     * 清除Token
     * @access public
     * @param  string $token Token标记
     * @return boolean
     */
    public static function clear($user_id = null)
    {
        $keys = self::tokens($user_id);
        $redis = Redis::init();
        $redis->del( self::getUserKey($user_id) );
        $redis->del($keys);
        return true;
    }

    protected static function getTokenKey($token)
    {
        return self::$tokenPrefix.$token;
    }

    protected static function getUserKey($user_id)
    {
        return self::$userPrefix.$user_id;
    }

}
